angular.module('myApp')
  .factory('debounce', function ($timeout) {
    return function (func, wait) {
      let timeoutPromise;
      return function (...args) {
        const context = this;
        if (timeoutPromise) $timeout.cancel(timeoutPromise);
        timeoutPromise = $timeout(function() { func.apply(context, args) }, wait);
      };
    };
  })
  .service('ColorService', function() {
    this.darken = function(hex, percent) {
      // 参数校验
      if (!hex || !/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/.test(hex)) return hex;
      percent = Math.min(Math.max(parseInt(percent) || 0, 0), 100);
  
      // 移除#号并扩展缩写
      hex = hex.replace('#', '');
      if (hex.length === 3) {
        hex = hex.split('').map(function(c) {
          return c + c;
        }).join('');
      }
  
      // 分解颜色通道
      var r = parseInt(hex.substr(0,2), 16);
      var g = parseInt(hex.substr(2,2), 16);
      var b = parseInt(hex.substr(4,2), 16);
  
      // 应用加深计算
      var ratio = 1 - (percent / 100);
      return '#' + [
        Math.round(r * ratio),
        Math.round(g * ratio),
        Math.round(b * ratio)
      ].map(function(c) {
        return ('0' + c.toString(16)).slice(-2);
      }).join('');
    };
  });